import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { getToken, removeToken } from "./localStorage";
import config from "@/common/config/request";
import { fetchUserInfo } from "@/store/slices/userInfo";
import { store } from "@/store";

const NOTTOKEN = ["login", "forgot", "register"];
const whiteList = [
  "swap/swap",
  "market/order",
  "goods/upgrade",
  "user/withdrawal",
  "user/transfer",
  "user/recharge",
  "swap/exchange",
  "user/getAccountRecord",
  "goods/upgrade",
  "market/orderBuy",
];
const reqHashMap = new Map();
const httpService = axios.create({
  // 判断运行环境
  // baseURL: '/api/',
  baseURL:
    process.env.NODE_ENV === "development"
      ? config.dev_base_url
      : config.pro_base_url,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});
httpService.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  if (reqHashMap.has(config.url)) {
    let cancal = reqHashMap.get(config.url);
    cancal();
    reqHashMap.delete(config.url);
  }
  config.headers["Token"] = getToken();
  // console.log(config.data)
  if (config.data && config.data["APITOKEN"]) {
    config.headers["APITOKEN"] = config.data["APITOKEN"];
  }
  const CancalToken = axios.CancelToken;
  const source = CancalToken.source();
  config.cancelToken = source.token;
  if (config.url !== "market/getSaleList") {
    reqHashMap.set(config.url, source.cancel);
  }
  return config;
});
httpService.interceptors.response.use(
  async (res: AxiosResponse) => {
    reqHashMap.delete(res.config.url);
    if (
      res.data.code == 401 &&
      !NOTTOKEN.some((item) => location.hash.includes(item))
    ) {
      removeToken();
      location.href = "/#/";
      return;
    }
    if (
      whiteList.includes(res.config.url as string) &&
      res.data.code == 0 &&
      !res.data.data.calculate
    ) {
      store.dispatch(fetchUserInfo());
    }
    return res.data;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// const request = (url: string, method: string, data: any) => {
//   return httpService({
//     url,
//     method,
//     data
//   })
// }

export default httpService;
